// ignore_for_file: unused_local_variable, unnecessary_null_comparison

import 'package:dio/dio.dart';

import 'package:get/utils.dart';
import 'package:open_file/open_file.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

var _savePath = '';
var updateUrl = 'https://www.xyfcoco.top/app_update/version.json';
var apkAddress = 'https://www.xyfcoco.top/app_update/app-release.apk';

class UpdateApp {
  static Future<bool> checkUpdate() async {
    // DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    // AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    // var temp = androidInfo.version.toString();

    PackageInfo packageInfo = await PackageInfo.fromPlatform();

    String appName = packageInfo.appName;
    String packageName = packageInfo.packageName;
    String version = packageInfo.version;
    Dio dio = Dio();
    Response<dynamic> res = await dio.get(updateUrl);
    // print(res.data);
    if (res != null && res.data['version'] == version) {
      return false;
    }
    return true;
  }

  /**
 *  获取文件存储路径
 * */
  static _getSavePath() async {
    var directory = await getExternalStorageDirectory();
    String storageDirectory = directory!.path;
    _savePath = storageDirectory;
  }

  /**
 *  检测存储权限
 * */
  static Future<bool> _checkPermission() async {
    if (GetPlatform.isAndroid) {
      final status = await Permission.storage.status;
      if (status != PermissionStatus.granted) {
        final result = await Permission.storage.request();
        if (result == PermissionStatus.granted) {
          return true;
        } else {
          return false;
        }
      } else {
        return true;
      }
    }
    return false;
  }

  /**
 *  下载应用
 * */
  static download(Function callBack) async {
    var flag = await _checkPermission();
    if (flag) {
      await _getSavePath();
      String appName = "bby.apk";
      String downPath = "$_savePath/$appName";
      String apkUrl = apkAddress; //远程应用地址
      Dio dio = Dio();
      await dio.download(apkUrl, downPath,
          onReceiveProgress: (int count, int total) {
        callBack("${(count / total * 100).toStringAsFixed(0)}");
      });

      await OpenFile.open(downPath,
          type: "application/vnd.android.package-archive");
    }
  }
}
